﻿using AutoMapper;
using PowerHub.MES.Common.Utility;
using PowerHub.MES.DTO.BasicData.DTO;
using PowerHub.MES.DTO.BasicData.QueryDto;
using PowerHub.MES.EFBase;
using PowerHub.MES.Entities;
using PowerHub.MES.Entities.BasicData;
using PowerHub.MES.IRepository.IBasic;
using PowerHub.MES.IServices.IBasic;
using PowerHub.MES.Jwt;
using PowerHub.MES.ReturnEntity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace PowerHub.MES.Services.Basic
{
    /// <summary>
    /// 用户接口实现层
    /// </summary>
    public class BasicDataUserinfoServices : BaseServices<BasicData_Userinfo>, IBasicDataUserinfoServices
    {
        private IBasicDataUserinfoRepository _IbasicDataUserinfoRepository;
        public JwtService _jwtService;
        private IMapper _mapper;
        private static Random random = new Random();
        public UserServices _userServices;

        public BasicDataUserinfoServices(PowerHubMesContext powerHubMesContext, IBasicDataUserinfoRepository ibasicDataUserinfoRepository, JwtService jwtService, IMapper mapper, UserServices userServices) : base(powerHubMesContext)
        {
            _IbasicDataUserinfoRepository = ibasicDataUserinfoRepository;
            _jwtService = jwtService;
            _mapper = mapper;
            _userServices = userServices;
        }


        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<OperationResult<string>> apiLogin(QueryBasicData_UserinfoDTO query)
        {
            var result = new OperationResult<string>();

            BasicData_Userinfo basicData_Userinfo = await GetEntityAsync(u => u.JobNumber.Equals(query.JobNumber));
            if (basicData_Userinfo == null)
            {
                throw new Exception("你似乎还没有注册呢，兄dei");
            }
            else if (!basicData_Userinfo.Password.Equals(MD5Helper.getMd5String(query.Password)))
            {
                throw new Exception("密码错了，是不是手滑了兄dei");
            }

            // 将用户id和角色名，作为单独的自定义变量封装进 token 字符串中。
            TokenModel tokenModel = new TokenModel { Uid = basicData_Userinfo.Id, UserName = basicData_Userinfo.UserName, Role = basicData_Userinfo.RoleinfoId };

            string jwtStr = _jwtService.GenerateJwtToken(new Claim(ClaimTypes.Authentication, DateTime.Now.Ticks.ToString()), tokenModel, DateTime.UtcNow.AddHours(3));//获取到一定规则的 Token 令牌
            result.Data = jwtStr;

            return result;
        }



        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<OperationResult<object>> CreateBasicData_UserinfoAsync(BasicData_UserinfoDTO query)
        {
            var result = new OperationResult<object>();
            result.Data = false;
            //实体转换
            var basicData_Userinfo = _mapper.Map<BasicData_Userinfo>(query);
            basicData_Userinfo.Id = Guid.NewGuid().ToString();
            basicData_Userinfo.JobNumber = GetJobNumber();
            basicData_Userinfo.Password = MD5Helper.getMd5String("123");
            basicData_Userinfo.Creator = _userServices.UserName;

            if (await _IbasicDataUserinfoRepository.CreateBasicData_UserinfoAsyncRepository(basicData_Userinfo) > 0)
            {
                result.Data = true;
            }

            return result;
        }


        //生成工号  
        public string GetJobNumber(string customCode = "63", int sequenceLength = 5)
        {
            BasicData_Userinfo basicData_Userinfo = GetEntityListAsync(u => u.IsDel == 0).Result.OrderByDescending(u => u.JobNumber).FirstOrDefault();

            int sequenceNumber = 0;
            if (basicData_Userinfo != null)
            {
                string JobNumber = basicData_Userinfo.JobNumber.Substring(basicData_Userinfo.JobNumber.Length - 5);
                sequenceNumber = Convert.ToInt32(JobNumber);
               
            }
            // 获取当前年份的简写（只取后两位）  
            string yearShort = DateTime.Now.Year.ToString().Substring(2, 2);

            // 生成顺序号
            sequenceNumber++;

            // 确保顺序号的长度符合指定要求，如果不足则在前面补零  
            string sequence = sequenceNumber.ToString().PadLeft(sequenceLength, '0');

            // 拼接工号  
            return yearShort + customCode + sequence;
        }


     
        /// <summary>
        /// 批量删除用户
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<OperationResult<object>> BatchDeletionBasicData_UserinfoAsync(List<string>? ids)
        {
            if (ids.Count < 1)
            {
                throw new Exception("请先选择数据！");
            }
            return await _IbasicDataUserinfoRepository.BatchDeletionBasicData_UserinfoAsyncRepository(ids);
        }

        /// <summary>
        ///更新用户
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<OperationResult<object>> UpdateBasicData_UserinfoAsync(BasicData_UserinfoDTO query)
        {
            if (query == null)
            {
                throw new Exception("请先选择数据！");
            }

            BasicData_Userinfo basicData_Userinfo = _mapper.Map<BasicData_Userinfo>(query);
            basicData_Userinfo.Updator = _userServices.UserName;

            return await _IbasicDataUserinfoRepository.UpdateBasicData_UserinfoAsyncRepository(basicData_Userinfo);
        }


        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<OperationPageResult<List<BasicData_Userinfo>>> GetBasicData_UserinfoPageListAsync(QueryBasicData_UserinfoDTO query)
        {
            return await _IbasicDataUserinfoRepository.GetPageListAsync(query);
        }
    }
}
